package cn.getech.data.development.service.impl;

import cn.getech.data.development.entity.*;
import cn.getech.data.development.mapper.JobDepHistoryLogMapper;
import cn.getech.data.development.model.dto.SaveAlarmLogDto;
import cn.getech.data.development.model.vo.AlarmTaskLogVO;
import cn.getech.data.development.service.*;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;

/**
 * @ClassName SaveAlarmLogServiceImpl
 * @Description TODO
 * @Author Getech
 * @Date 2020/12/14 16:03
 */
@Service
public class SaveAlarmLogServiceImpl implements SaveAlarmLogService {

    @Autowired
    private IBdpAlarmLogService bdpAlarmLogService;
    @Autowired
    private AlarmObjectService alarmObjectService;
    @Autowired
    private WorkMenuServiceImpl workMenuService;

    @Autowired
    private WorkFlowDepServiceImpl workFlowDepService;
    @Autowired
    private ProcInfoService procInfoService;
    @Autowired
    private JobRunHistoryService jobRunHistoryService;
    @Autowired
    private JobInfoService jobInfoService;
    @Autowired
    private JobDepHistoryLogMapper jobDepHistoryLogMapper;
    @Autowired
    private AlarmService alarmService;

    @Override
    public Long saveAlarmLog(SaveAlarmLogDto saveAlarmLogDto){

        BdpAlarmLog bdpAlarmLog=new BdpAlarmLog();
        try{
            Alarm alarm= saveAlarmLogDto.getAlarm();
            BeanUtil.copyProperties(alarm,bdpAlarmLog);
            bdpAlarmLog.setAlarmTime(saveAlarmLogDto.getAlarmTime());
            String sendConent="告警邮件主题：【"+saveAlarmLogDto.getMailSubject()+"】邮件内容:"+ saveAlarmLogDto.getMailContent();
            bdpAlarmLog.setSendContent(sendConent);
            bdpAlarmLog.setId(null);
            bdpAlarmLog.setAlarmId(alarm.getId());
            bdpAlarmLog.setReceivedUserMail(saveAlarmLogDto.getMailAddress());
            bdpAlarmLog.setReceivedUserId(saveAlarmLogDto.getReceiverUserId());
            bdpAlarmLog.setSendState(saveAlarmLogDto.getSendState());
            bdpAlarmLog.setObjectName(saveAlarmLogDto.getWorkflowName());
            bdpAlarmLog.setCreateTime(LocalDateTime.now());
            bdpAlarmLogService.save(bdpAlarmLog);
        }catch (Exception e){
            e.printStackTrace();
        }

        return bdpAlarmLog.getId();
    }


    /**
     * @Description  修改发送状态
     * @Author  chengweiping
     * @Date   2020/12/14 16:45
     */
    @Override
    public void updateStatus(Long alarmLogId, Integer status){
        try{
            if(alarmLogId==null){
                return ;
            }
            BdpAlarmLog bdpAlarmLog= bdpAlarmLogService.getById(alarmLogId);
            bdpAlarmLog.setSendState(status);
            bdpAlarmLog.setUpdateTime(LocalDateTime.now());
            bdpAlarmLogService.updateById(bdpAlarmLog);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 根据任务告警id 查询需要的日志数据
     * @param
     * @return
     */
    public AlarmTaskLogVO queryBdpAlarmLogId(Long alarmLogId){
        AlarmTaskLogVO alarmTaskLogVO = new AlarmTaskLogVO();
        //先获取 alarm的id
        BdpAlarmLog bdpAlarmLog= bdpAlarmLogService.getById(alarmLogId);
        Alarm byId1 = alarmService.getById(bdpAlarmLog.getAlarmId());
        System.out.println("准备告警邮件-alarm新:"+ JSON.toJSONString(byId1));
        //作业流类型
        alarmTaskLogVO.setAlarmType(byId1.getTriggerCondition()==0?"作业流运行失败":"作业流运行成功");
        //任务创建人
        alarmTaskLogVO.setAlarmUser(byId1.getCreatePer().longValue());
        //任务名称
        alarmTaskLogVO.setName(byId1.getName());
        List<AlarmObject> alarmObjects = alarmObjectService.listByalarmId(bdpAlarmLog.getAlarmId().longValue());
        alarmObjects.sort(Comparator.comparing(AlarmObject::getId).reversed());
        //执行节点信息
        WorkMenu byId2 = workMenuService.getById(alarmObjects.get(0).getObjectId());
        alarmTaskLogVO.setWorkflowName(byId2.getName());
        System.out.println("准备告警邮件-执行节点信息:"+ JSON.toJSONString(byId2));
        //取项目信息
        ProcInfo procInfo = procInfoService.getById(byId2.getProcId());
        //项目名称
        alarmTaskLogVO.setProcName(procInfo.getName());
        //项目创建人
        alarmTaskLogVO.setProcUser(procInfo.getCreatePer().longValue());
        //获取jobinfo信息  通过这个jobinfo信息获取日志信息
        LambdaQueryWrapper<JobInfo> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(JobInfo::getProcId,byId2.getProcId());
        lambdaQuery.eq(JobInfo::getName,byId2.getName());
        lambdaQuery.last("LIMIT 1");
        JobInfo one = jobInfoService.getOne(lambdaQuery);
        System.out.println("准备告警邮件-获取jobinfo信息  通过这个jobinfo信息获取日志信息:"+ JSON.toJSONString(one));

        //获取节点日志执行节点记录(最新一条)
        LambdaQueryWrapper<JobRunHistory> jobRunHistoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        jobRunHistoryLambdaQueryWrapper.eq(JobRunHistory::getJobInfoId,one.getId());
        jobRunHistoryLambdaQueryWrapper.orderByDesc(JobRunHistory::getId);
        jobRunHistoryLambdaQueryWrapper.last(" LIMIT 1");
        JobRunHistory one1 = jobRunHistoryService.getOne(jobRunHistoryLambdaQueryWrapper);
        //获取cronName
        List<JobNodeConf> jobNodeConfs = workMenuService.listWorkFlowConfig(byId2.getId());
        if (CollectionUtil.isNotEmpty(jobNodeConfs)) {
            for (JobNodeConf jobNodeConf : jobNodeConfs) {
                //1 正常调度  0或者空 暂停调度
                if ("scheduleType".equals(jobNodeConf.getKey()) &&"1".equals(jobNodeConf.getValue())){
                    // 1  手動配置  2 crontab表達式
                    if ("cronType".equals(jobNodeConf.getKey())&& "2".equals(jobNodeConf.getValue())){
                        if("cronUrl".equals(jobNodeConf.getKey())){
                            alarmTaskLogVO.setCronName(jobNodeConf.getValue());
                        }
                    }else {
                        alarmTaskLogVO.setCronName("手动配置");
                    }
                }else {
                    alarmTaskLogVO.setCronName("暂停调度");
                }
            }
        }
        System.out.println("准备告警邮件-获取节点执行节点记录(最新一条):"+ JSON.toJSONString(one1));
        System.out.println("发送的其他信息:"+ JSON.toJSONString(alarmTaskLogVO));
        //日志信息
        String log = jobRunHistoryService.getLog(one1.getId());
        alarmTaskLogVO.setLogin(log);
        return alarmTaskLogVO;
    }
}
